package com.example.demo.controller;

import com.example.demo.constant.Code;
import com.example.demo.pojo.Result;
import com.example.demo.pojo.dto.SmsSendDTO;
import com.example.demo.pojo.properties.AliyunSmsProperties;
import com.example.demo.utils.AliyunSmsUtil;
import com.example.demo.utils.VerificationCodeUtil;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
public class AliyunSmsController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate; //报错信息错误，无影响
    @Autowired
    private AliyunSmsProperties aliyunSmsProperties;

    @PostMapping("/send")
    public Result smsSend(@RequestBody @Valid SmsSendDTO smsSendDTO) {
        String phone = smsSendDTO.getPhone();

        String randomCode = VerificationCodeUtil.generateRandomCode();

        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(phone, randomCode, 3, TimeUnit.MINUTES);

        try {
            Map<String, String> result = AliyunSmsUtil.sendDigitSms(aliyunSmsProperties, phone, randomCode);

            String codeResult = result.get("code");
            String message = result.get("message");

            int code = (codeResult.equals("OK")) ? Code.SMS_OK : Code.SMS_ERR;

            return new Result(code, codeResult, message);

        } catch (Exception exception) {
            exception.printStackTrace();
            return new Result(Code.SMS_ERR, null, "短信验证码发送错误，请重试");
        }
    }
}
